package com.example.day10;

import com.example.day09.DB;
import com.mysql.jdbc.Driver;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

// Ctrl + Alt + O

public class CSDN {
    private static final String SQL = "INSERT INTO db_csdn.csdn VALUES(NULL, ?, ?, ?)";
    private static final int BATCH_SIZE = 100000;

    public static void main(String[] args) throws SQLException, IOException {

        Connection connection = DBCPDatasource.getConnection();
        connection.setAutoCommit(false);
        PreparedStatement preparedStatement = connection.prepareStatement(SQL);

        BufferedReader bufferedReader = new BufferedReader(new FileReader("www.csdn.net.sql"));

        int counter = 0;
        String line;
        String[] strings;
        long sartTime = System.currentTimeMillis();
        while ((line = bufferedReader.readLine()) != null) {
            strings = line.split(" # ");
            String username = strings[0];
            String password = strings[1];
            String email = strings[2];

            // save to MySQL
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            preparedStatement.setString(3, email);

            preparedStatement.addBatch();
            counter++;

            if (counter % BATCH_SIZE == 0) {
                preparedStatement.executeBatch();
                System.out.println(counter + " data inserted.");
            }
        }
        preparedStatement.executeBatch();

        connection.commit();

        long endTime = System.currentTimeMillis();

        preparedStatement.close();
        connection.close();

        System.out.println("total datas: " + counter);
        System.out.println((endTime - sartTime) + " ms.");
    }
}